/**
 * A transparent "glass" pane is a layer between modal dialog and the top window.
 * It used to intercept mouse events when the dialog becomes modal.
 *
 * @author Andrey Anisimov <hercules@inbox.ru>
 */

import core.ui.Window;

class ModalGlassPane extends Window {

	/**
	 * Initializes the modal glass pane.
	 */
	this.ModalGlassPane = function() {
		super();
		this.zIndexes = [];
		this.dialogs = [];
		this.setStyle('z-index', 0);
		Window.addListener(this);
		this.updateLayout();
	}

	/**
	 * Makes the dialog modal enter the modal state.
	 *
	 * @param dialog (Dialog) The dialog to make modal.
	 */
	this.modalize = function(dialog) {
		this.dialogs.push(dialog);
		this.move(0, 0);
		this.resize(Window.getWidth(), Window.getHeight());
		this.zIndexes.push(this.getStyle('z-index'));
		this.activate();
		this.show();
		dialog.activate();
		dialog.show();
	}

	/**
	 * Makes the dialog finish the modal state.
	 *
	 * @param dialog (Dialog) The dialog to make unmodal.
	 */
	this.unmodalize = function(dialog) {
		this.setStyle('z-index', this.zIndexes.pop());
		this.dialogs.pop();
		if (0 == this.dialogs.length) {
			this.hide();
		}
		dialog.hide();
	}

	/**
	 * Returns the currently active modal dialog.
	 *
	 * @return Dialog
	 */
	this.getActiveDialog = function() {
		return this.dialogs[this.dialogs.length - 1];
	}

	/**
	 * Updates the pane size and layout.
	 */
	this.updateLayout = function() {
		this.resize(Window.getWidth(), Window.getHeight());
	}

	this.onWindowResized =
	this.onWindowScrolled = function() {
		this.updateLayout();
	}

	this.onmousedown = function() {
		this.getActiveDialog().fireLooseActivity();
	}
}

/**
 * Returns the singleton instance of the glass pane.
 * 
 * @return ModalGlassPane
 */
ModalGlassPane.getInstance = function() {
	if (!this.instance) {
		this.instance = new ModalGlassPane();
	}
	return this.instance;
}